package com.wisezone.net.client1;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * socket客户端程序 1.实例socket 发起socket连接
 * 
 * @author Administrator
 *
 */
public class ClientSocket {
	private static final String HOST = "192.168.5.6";
	private static final int PORT = 9527;
	private Socket socket;

	public ClientSocket() {
		try {
			socket = new Socket(HOST, PORT); // 发起socket请求
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 发送消息
	 */
	public void sendMessage(String message) {
		try {
			PrintWriter pw = new PrintWriter(socket.getOutputStream());
			pw.println(message);
			pw.flush();

		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 从键盘读信息发送
	 */
	public void sendMessage() {
		while (true) {
			String message = readMessageByKeyBoard();
			sendMessage(message);
		}
	}

	/**
	 * 从键盘读信息
	 */
	public String readMessageByKeyBoard() {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String line = "";
		try {
//			System.out.println("客户端: ");
			line = br.readLine();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return line;
	}

	/**
	 * 读消息
	 *
	 */
	public String readMessage() {
		String line = null;
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			line = br.readLine();

		} catch (IOException e) {
			e.printStackTrace();
			close();
		}
		return line;
	}

	/**
	 * 一直接收消息
	 */
	public void receiveMesage() {
		while (true) {
			String message = readMessage();
			if (message != null) {
				System.out.println("服务端: "+message);
			}
		}
	}

	/**
	 * 关闭socket
	 */
	public void close() {
		try {
			if (socket != null)
				socket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
